# -*- coding: utf-8 -*-
import functools
import json
import logging
import time

import itchat
import multimethod as multimethod
import requests

from itchat.content import *

from utils import Mongo_DBHelper
from utils.Mongo_DBHelper import getGirdFsPipline

apiUrl = 'http://openapi.tuling123.com/openapi/api/v2'

headers = {
    'Content-Type': "application/json",
    'charset': "utf-8"
}

logger = logging.getLogger("itchat")

chartromm = None

#
# @itchat.msg_register(TEXT, isGroupChat=True)
# def get_conversationt_content(msg):
#     content = msg['Text']
#     return content
#
#
# @itchat.msg_register(TEXT, isGroupChat=True)
# def get_MsgId(msg):
#     msgId = msg['MsgId']
#     print(msgId)
#
#
# @itchat.msg_register(TEXT, isGroupChat=True)
# def get_chatroom(msg):
#     chatroom = msg['User']['NickName']
#     return chatroom
#
#
# @itchat.msg_register(TEXT, isGroupChat=True)
# def get_record(msg, replay=None):
#     global chartromm
#     chartromm = get_chatroom(msg)
#     if replay is not None:
#         record['content'] = replay
#     else:
#         record['content'] = get_conversationt_content(msg)
#     record['chartroom'] = chartromm
#
#     return record


if __name__ == '__main__':

    def make_payload(appKey, userid, ask):
        payload = {
            "reqType": 0,
            "perception": {
                "inputText": {
                    "text": str(ask)
                }
            },
            "userInfo": {
                "apiKey": str(appKey),
                "userId": str(userid)
            }
        }

        data = json.dumps(payload)
        return data


    itchat.auto_login(hotReload=True, enableCmdQR=2)


    #
    # @itchat.msg_register(TEXT, isGroupChat=True)
    def msg_record(msg):
        msg['Text'] = None
        msgObj = json.dumps(msg)
        collection = Mongo_DBHelper.getCollection()
        item = json.loads(msgObj)
        collection.insert(item)


    def get_recorder(**kwargs):
        record = dict()

        if kwargs.get("msg"):
            msg = kwargs['msg']

        if kwargs.get("replay"):
            replay = kwargs['replay']
            record['content'] = replay
            record['time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


    @itchat.msg_register(TEXT, isGroupChat=True)
    def tuling_reply(msg):
        app_key = "f985d7f97dab4fe49d21c32e6aca3ab1"
        user_id = "e63857aa506e412185ea2a2e7fdaa1ff"
        # df = itchat.search_chatrooms(name="123我们都是机器人")
        prefix = "@".join(msg['User']['Self']['NickName'])
        if msg['IsAt']:
            req = msg['Text'].lstrip(prefix)
            data = make_payload(app_key, user_id, req)
            response = requests.request("POST", apiUrl, data=data, headers=headers)
            ack = json.loads(response.content)
            content = ack['results'][0]['values']['text']
            msg_record(msg)
            return content
        else:
            msg_record(msg)


    itchat.run(debug=True)
